# 导入所需库
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score, classification_report

# 示例数据集：邮件内容及其标签（1表示垃圾邮件，0表示正常邮件）
emails = [
    "Win a free iPhone now! Click here to claim your prize.",
    "Hi John, can we schedule a meeting for tomorrow?",
    "Congratulations! You've won a $1000 gift card. Claim it now!",
    "Please find attached the report you requested.",
    "Earn money fast with this amazing opportunity!",
    "Let's catch up over coffee this weekend."
]
labels = [1, 0, 1, 0, 1, 0]  # 1: 垃圾邮件, 0: 正常邮件

# 将文本数据转换为数值特征向量
vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(emails)  # 特征矩阵

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, labels, test_size=0.3, random_state=42)

# 创建并训练SVM模型
svm_model = SVC(kernel='linear')  # 使用线性核函数
svm_model.fit(X_train, y_train)

# 在测试集上进行预测
y_pred = svm_model.predict(X_test)

# 输出结果
print("Accuracy:", accuracy_score(y_test, y_pred))
print("\nClassification Report:\n", classification_report(y_test, y_pred))

# 测试新邮件
new_email = ["Claim your reward now! Limited time offer."]
new_email_vectorized = vectorizer.transform(new_email)
prediction = svm_model.predict(new_email_vectorized)
print("\nNew Email Prediction:", "Spam" if prediction[0] == 1 else "Not Spam")